<template>
  <div>
    <div @click="applynewadd()">
      <slot>
        <el-button type="primary">{{ title }}</el-button>
      </slot>
    </div>
    <MyDialog
      :title="title"
      :visible.sync="addSwitch"
      size="mini"
      @beforeClose="close_add"
    >
      <div
        v-loading="detailLoading"
        style="margin-top: 20px"
        class="add-detail"
      >
        <el-form
          ref="elForm"
          class="addFrom"
          :model="queryParam"
          :rules="rules"
          label-width="100px"
        >
          <el-row :gutter="40" type="flex">
            <el-col :span="24">
              <el-form-item label="上级目录:" prop="parentId">
                <el-cascader
                  v-model="queryParam.parentId"
                  v-removeAriaHidden
                  :options="options"
                  style="width: 80%"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    value: 'id',
                    label: 'name',
                    children: 'childList',
                  }"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40" type="flex">
            <el-col :span="24">
              <el-form-item label="目录名称:" prop="name">
                <el-input
                  v-model="queryParam.name"
                  maxlength="30"
                  style="width: 80%"
                  clearable
                  placeholder="请输入"
                >
                  <span slot="suffix"></span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template slot="footer">
        <el-button type="primary" :loading="loading" @click="submit_apply">
          保 存
        </el-button>
        <el-button @click="close_add">取 消</el-button>
      </template>
    </MyDialog>
  </div>
</template>
<script>
  import MyDialog from '@/components/Dialog'
  import {
    adddepCategory,
    editCategory,
    depCategoryList,
  } from '@/api/dep/index.js'
  export default {
    components: {
      MyDialog,
    },
    data () {
      return {
        queryParam: {
          parentId: '',
          name: '',
          id: '',
        },
        addSwitch: false,
        loading: false,
        uploadList: false,
        rules: {
          name: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        editId: '',
        detailLoading: false,
        type: '',
        title: '新增目录',
        options: [],
      }
    },
    computed: {},
    watch: {},
    created () {},
    methods: {
      async applynewadd (item, type) {
        await this.getList()
        this.addSwitch = true
        this.uploadList = false
        this.loading = false
        this.type = ''
        if (item) {
          this.title = '修改目录'
          this.editId = item.id
          this.type = type
          this.queryParam.name = item.name
          this.queryParam.id = item.id

          let parentId = this.findParents(this.options, this.queryParam.id)
          this.queryParam.parentId = parentId
            ? parentId[parentId.length - 2]
            : ''
        }
      },

      findParents (treeData, childId, parents = []) {
        for (let i = 0; i < treeData.length; i++) {
          const node = treeData[i]
          if (node.id === childId) {
            // 找到了目标子节点，返回其所有父节点id
            return [...parents, node.id]
          } else if (node.childList && node.childList.length > 0) {
            // 递归遍历子节点的所有子节点
            const result = this.findParents(node.childList, childId, [
              ...parents,
              node.id,
            ])
            if (result) {
              // 找到了目标子节点，返回其所有父节点id
              return result
            }
          }
        }
        // 没有找到目标子节点
        return null
      },
      async getList () {
        let data = await depCategoryList()
        this.options = data.result
      },
      submit_apply () {
        this.$refs['elForm'].validate(async (valid) => {
          if (valid) {
            this.$confirm('是否继续此操作?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(async () => {
                try {
                  this.uploadList = true
                  this.loading = true
                  let params = { ...this.queryParam }
                  if (this.type == 'edit') {
                    params.id = this.editId
                    await editCategory(params)
                    this.$message({
                      message: '修改成功',
                      type: 'success',
                    })
                  } else {
                    await adddepCategory(params)
                    this.$message({
                      message: '新增成功',
                      type: 'success',
                    })
                  }
                  setTimeout(() => {
                    this.close_add()
                  }, 500)
                } catch (error) {
                  this.loading = false
                }
              })
              .catch(() => {})
          } else {
            return false
          }
        })
      },

      close_add () {
        this.$refs['elForm'].resetFields()
        this.$nextTick(() => {
          if (this.uploadList) {
            this.$emit('load')
          }
          this.addSwitch = false
        })
      },
    },
  }
</script>
<style scoped lang="scss">
  .addFrom {
    width: 100%;
    overflow: hidden;
  }

  .df-end {
    display: flex;
    justify-content: flex-end;
  }

  .upload-box {
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed #c0ccda;
    cursor: pointer;
  }

  .live-style-item {
    float: right;
    color: #8492a6;
    font-size: 13px;
    max-width: 200px;
  }

  .bind-box {
    padding: 0 0 20px;
  }

  .bind-box-table {
    padding: 0 0 20px;
  }

  .footer {
    text-align: center;
    padding: 10px 0 45px;

    & > :nth-child(n + 2) {
      margin-left: 14px;
    }

    button {
      width: 106px;
      height: 48px;
    }
  }
</style>
